package com.red.star.macalline.sched.service;

import com.red.star.macalline.data.entity.*;
import com.red.star.macalline.data.mappers.ClientHideMapper;
import com.red.star.macalline.data.repository.ChatListRepository;
import com.red.star.macalline.data.repository.ChatSessionRepository;
import com.red.star.macalline.data.utils.CheckUtil;
import com.red.star.macalline.sched.entity.ActiveChat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

/**
 * @author nofish.yan@gmail.com
 * @date 2018/3/19.
 * 客户端服务类
 */
@Service
public class ClientService {

    private Logger logger = LoggerFactory.getLogger(ClientService.class);

    @Resource
    private ClientHideMapper clientHideMapper;

    @Resource
    private ChatListRepository chatListRepository;

    @Resource
    private ChatSessionRepository chatSessionRepository;

    @Value("${sched.sms.cActiveTime}")
    private Integer cActiveTime = 15;

    @Value("${sched.sms.bActiveTime}")
    private Integer bActiveTime = 15;

    /**
     * 筛选条件：
     * 1.30分钟内无操作
     * 2.30分钟内有用户向其发送消息
     *
     * @return 满足条件的用户集合
     */
    public List<ActiveChat> listFansWithChatSessionInTime() {
        List<ActiveChat> result = new ArrayList<>();
        List<ClientLife> clientLives = filterFansBySmsLog();
        // 找出三十分钟内有会话的用户
        List<ChatList> chatLists = chatListRepository.findActiveUserInThirtyMinute();
        // 遍历30分钟内无操作的用户，找出30分钟内有消息的用户
        for (ChatList chatList : chatLists) {
            // 无会话
            if (chatList == null || CheckUtil.isEmpty(chatList.getChatUsers())) {
                logger.debug("无最近联系人");
                continue;
            }
            ActiveChat activeChat = getInactivityFansOverThirtyMinute(chatList, clientLives);
            if (activeChat != null) {
                result.add(activeChat);
            }
        }
        return result;
    }

    /**
     * 查询条件：
     * 1.30分钟无交互
     * 2.30分钟内未发送过短信
     *
     * @return
     */
    private List<ClientLife> filterFansBySmsLog() {
        // 超过三十分钟无操作的客户端(当日内活跃用户）
        return clientHideMapper.findClientAndMobileBySmsLogNew(cActiveTime, bActiveTime);
    }

    /**
     * 匹配30分钟内无操作的客户端用户
     *
     * @param chatList    用户对话列表
     * @param clientLives 30分钟无操作用户列表
     * @return 匹配的用户ID
     */
    private ActiveChat getInactivityFansOverThirtyMinute(ChatList chatList, List<ClientLife> clientLives) {
        for (ClientLife clientLife : clientLives) {
            // 当前用户30分钟内收到消息
            if (clientLife.getFansId().equals(chatList.getFansId())) {
                // 遍历会话，知道查找到一个满足条件则返回
                for (ChatUser chatUser : chatList.getChatUsers()) {
                    ActiveChat activeChat = getChatFansInThirtyMinute(chatList.getFansId(), chatUser.getChatSessionId());
                    if (activeChat != null) {
                        activeChat.setMobile(clientLife.getMobile());
                        return activeChat;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 查找某个会话中是否有人回复
     *
     * @param fansId        当前用户ID
     * @param chatSessionId 会话ID
     * @return 回复的用户ID
     */
    private ActiveChat getChatFansInThirtyMinute(Integer fansId, String chatSessionId) {
        ChatSession chatSession = chatSessionRepository.findChatSessionById(chatSessionId);
        if (fansId.equals(chatSession.getCFansId())) {
            // 当前用户是C端用户，查找30分钟内是否有B端用户的消息
            if (chatSession != null && !CheckUtil.isEmpty(chatSession.getMessages())) {
                Collections.reverse(chatSession.getMessages());
                for (ChatMessage message : chatSession.getMessages()) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.MINUTE, -cActiveTime);
                    if (message.getCreateTime().before(calendar.getTime())) {
                        return null;
                    }
                    // 有B端用户发送消息，需要选取该用户
                    if (message.getBFansId() != null) {
                        // TODO: 2018/3/20 提取消息对象
                        ActiveChat activeChat = new ActiveChat();
                        activeChat.setFansId(fansId);
                        activeChat.setChatSessionId(chatSessionId);
                        activeChat.setChatFansId(message.getBFansId());
                        return activeChat;
                    }
                }
            }
        } else {
            // 当前用户是B端用户，查找30分钟内是否有C端用户的消息
            if (chatSession != null && !CheckUtil.isEmpty(chatSession.getMessages())) {
                Collections.reverse(chatSession.getMessages());
                for (ChatMessage message : chatSession.getMessages()) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.MINUTE, -bActiveTime);
                    if (message.getCreateTime().before(calendar.getTime())) {
                        return null;
                    }
                    // 有C端用户发送消息，需要选取该用户
                    if (message.getCFansId() != null) {
                        // TODO: 2018/3/20 提取消息对象
                        ActiveChat activeChat = new ActiveChat();
                        activeChat.setFansId(fansId);
                        activeChat.setChatSessionId(chatSessionId);
                        activeChat.setChatFansId(message.getCFansId());
                        return activeChat;
                    }
                }
            }
        }
        return null;
    }

}
